<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>深拷贝和浅拷贝</title>
</head>
<body>
<script>
    // 深拷贝拷贝多层, 每一集别的数据都要拷贝
    let obj = {
        id: 1,
        name: 'Alan',
        msg: {
            age: 18
        },
        color: ['pink', 'red']
    }
    let o = {}

    function deepCopy(newObj, oldObj) {
        for (let key in oldObj) {
            // 判断我们属性值属于那种数据类型
            // 1. 获取属性值 oldObj[key]
            let item = oldObj[key]
            // 2. 判断这个值是否是数组
            if (item instanceof Array) {
                newObj[key] = []
                deepCopy(newObj[key], item)
            } else if (item instanceof Object) {
                // 3. 判断这个值是否是对象
                newObj[key] = {}
                deepCopy(newObj[key], item)
            } else {
                // 4. 属于简单数据类型
                newObj[key] = item
            }

        }
    }
    deepCopy(o, obj)
    console.log(o)

    /* array对象 instanceof Object 为 true, array对象.constructor === Object 为 false */
    function deepClone(source) {
        if (!source && typeof source !== "object") {
            throw new Error('error arguments', 'shallowClone')
        }
        if (source === null) {
            throw new Error('error arguments', 'source')
        }
        const targetObj = source.constructor === Array ? [] : {};
        for (const key in source) {
            if (source.hasOwnProperty(key)) {
                if (source[key] && typeof source[key] === "object") {
                    targetObj[key] = deepClone(source[key])
                } else {
                    targetObj[key] = source[key]
                }
            }
        }
        return targetObj
    }
    console.log(deepClone(obj))

</script>
</body>
</html>
